import {
  LogoutOutlined,
  PlusCircleOutlined,
  SearchOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { ProSettings } from "@ant-design/pro-components";
import { ProConfigProvider, ProLayout } from "@ant-design/pro-components";
import { Avatar, ConfigProvider, Dropdown, Input, message, Tag } from "antd";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../store";
import { useNavigate } from "react-router-dom";
import notLoginImg from "./notLogin.png";
import { logoutUsingGet } from "../../api/userController.ts";
import { DEFAULT_USER, setLoginUser } from "../../store/loginUser.tsx";
import BaseResponseBoolean_ = API.BaseResponseBoolean_;

const SearchInput = () => {
  const [showList, setShowList] = useState(false); // 控制列表显示的状态
  return (
    <div
      key="SearchOutlined"
      aria-hidden
      style={{
        display: "flex",
        alignItems: "center",
        background: "#e0e0e1",
        marginInlineEnd: 12,
        width: 350,
        position: "relative", // 使列表绝对定位
      }}
      onMouseDown={(e) => {
        e.stopPropagation();
        e.preventDefault();
      }}
      onFocus={() => setShowList(true)} // 聚焦时显示列表
      onBlur={() => setShowList(false)} // 失去焦点时隐藏列表
    >
      <Input
        style={{
          borderRadius: 4,
          marginInlineEnd: 12,
        }}
        prefix={<SearchOutlined />}
        placeholder="请搜索您需要的内容"
        variant="borderless"
      />
      <div
        style={{
          position: "absolute",
          top: "100%", // 在输入框下方显示
          left: 0,
          background: "white",
          boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
          width: "100%",
          zIndex: 20,
          opacity: showList ? 1 : 0, // 根据状态调整透明度
          transition: "opacity 0.3s ease", // 过渡效果
          visibility: showList ? "visible" : "hidden", // 控制可见性
          borderRadius: "8px",
        }}
      >
        {showList && (
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              flexDirection: "column",
              padding: "0px 10px 10px 10px",
              background: "#f8f8f8",
              borderRadius: "8px",
              width: "100%",
            }}
          >
            {/* Search History Section */}
            <div
              style={{
                width: "100%",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h4 style={{ margin: "0 0" }}>搜索历史</h4>
              <button
                style={{
                  background: "none",
                  border: "none",
                  color: "#9499a0",
                  padding: "0",
                  fontSize: "13px",
                  cursor: "pointer",
                }}
              >
                清空
              </button>
              {/*    这里需要放tab列表*/}
            </div>
            <div
              style={{
                width: "100%",
                display: "flex",
                flexWrap: "wrap",
                maxHeight: "100px",
                overflowY: "auto",
                gap: "5px",
              }}
            >
              <Tag>程序员星轨</Tag>
              <Tag>程序员星轨</Tag>
              <Tag>程序员</Tag>
              <Tag>程序员星轨</Tag>
              <Tag>程序员星轨</Tag>
            </div>
            <div style={{ width: "50%" }}>
              <h4 style={{ margin: "0px 0px", height: "40px" }}>热门房间</h4>
              <div
                style={{ display: "flex", flexDirection: "column", gap: "5px" }}
              >
                {[
                  "星轨会议系统",
                  "神十九任务发布会",
                  "专访33岁传奇导演张铁杰",
                  "罗德里戈2024金球奖",
                  "李小龙徒弟香港同住李媛",
                  "GEN被镶拍手套现状",
                  "王老板被粉丝雇用",
                  "封神第三部定档",
                  "同住回复离巴等行为",
                  "壶子电影3天2.9万票房",
                ].map((item, index, arr) => {
                  // Only render every 2nd item as a new row
                  if (index % 2 === 0) {
                    return (
                      <div key={index} style={{ display: "flex", gap: "10px" }}>
                        {[arr[index], arr[index + 1]].map(
                          (subItem, subIndex) =>
                            subItem && (
                              <div
                                key={subIndex}
                                style={{
                                  display: "flex",
                                  fontSize: "14px",
                                  flex: 1,
                                  alignItems: "center",
                                  height: "30px",
                                }}
                              >
                                <span
                                  style={{
                                    width: "20px",
                                    color: "#ff4d4f",
                                  }}
                                >
                                  {index + subIndex + 1}
                                </span>
                                <span
                                  style={{
                                    flexGrow: 1,
                                    whiteSpace: "nowrap",
                                    overflow: "hidden",
                                    textOverflow: "ellipsis",
                                    width: "110px",
                                  }}
                                >
                                  {subItem}
                                </span>
                                <div
                                  style={{
                                    backgroundColor: "#fadb14",
                                    color: "#fff",
                                    borderRadius: "3px",
                                    padding: "0 4px",
                                    fontSize: "12px",
                                    marginLeft: "8px",
                                    height: "20px",
                                    display: "flex",
                                    alignItems: "center",
                                  }}
                                >
                                  热
                                </div>
                              </div>
                            ),
                        )}
                      </div>
                    );
                  }
                  return null;
                })}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default () => {
  const [settings] = useState<Partial<ProSettings> | undefined>({
    fixSiderbar: true,
    layout: "mix",
    splitMenus: true,
  });

  const [pathname, setPathname] = useState("/list/sub-page/sub-sub-page1");
  const [isSmallScreen, setIsSmallScreen] = useState(false);
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const handleResize = () => {
    setIsSmallScreen(window.innerWidth < 768);
  };

  //退出登录
  const logout = async () => {
    // 清除登录状态
    let res: BaseResponseBoolean_ = await logoutUsingGet();
    if (res.code == 200) {
      message.success("退出登陆成功");
      dispatch(setLoginUser(DEFAULT_USER));
    }
  };

  useEffect(() => {
    handleResize(); // 初始加载时计算屏幕大小
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return (
    <div id="test-pro-layout">
      <ProConfigProvider hashed={false}>
        <ConfigProvider>
          <ProLayout
            title={
              <div
                style={{ cursor: "pointer" }}
                onClick={() => navigate("/")} // 返回首页
              >
                星轨会议系统
              </div>
            }
            logo={
              <img
                src="https://xinggui-1311139524.cos.ap-guangzhou.myqcloud.com/logo.png"
                alt="logo"
                style={{
                  height: 32,
                  margin: "16px 0px 16px 0px",
                }}
                onClick={() => navigate("/")} // 返回首页
              />
            }
            bgLayoutImgList={[]} // 清空背景图片列表，防止渲染背景相关的结构
            location={{
              pathname,
            }}
            token={{
              header: {
                colorBgMenuItemSelected: "rgba(0,0,0,0.04)",
              },
            }}
            siderMenuType="group"
            menu={{
              collapsedShowGroupTitle: true,
            }}
            avatarProps={{
              src: loginUser.avatarUrl || notLoginImg,
              size: "small",
              title: loginUser.nickName || "未登录",
              render: (props, dom) => {
                return loginUser.id != -1 ? (
                  <Dropdown
                    menu={{
                      items: [
                        {
                          key: "userinfo",
                          icon: <UserOutlined />,
                          label: "个人中心",
                          onClick: () => {
                            navigate("/userInfo");
                          },
                        },
                        {
                          key: "logout",
                          icon: <LogoutOutlined />,
                          label: "退出登录",
                          onClick: () => {
                            logout();
                          },
                        },
                      ],
                    }}
                  >
                    {dom}
                  </Dropdown>
                ) : (
                  <div onClick={() => navigate("/login")}>
                    <Avatar icon={<UserOutlined />} />
                    <p className={"pl-1 pr-2"} style={{ fontSize: "17px" }}>
                      登录
                    </p>
                  </div>
                );
              },
            }}
            actionsRender={(props) => {
              return [
                props.layout !== "side" && document.body.clientWidth > 900 ? (
                  <SearchInput key="searchInput" />
                ) : undefined,
                !isSmallScreen ? (
                  <div
                    key="createRoom"
                    className="items-center hidden lg:block"
                  >
                    <div
                      className="flex"
                      onClick={() => {
                        navigate("/addRoom");
                      }}
                    >
                      <PlusCircleOutlined title="创建房间" />
                      <p className="pl-1">创建房间</p>
                    </div>
                  </div>
                ) : undefined,
                isSmallScreen ? (
                  <div
                    key="mobileSearch"
                    className="flex"
                    style={{
                      marginRight: "-25px",
                    }}
                    onClick={() => {
                      navigate("/search");
                    }}
                  >
                    <SearchOutlined title="搜索" />
                    <p className="pl-1">搜索</p>
                  </div>
                ) : undefined,
              ];
            }}
            onMenuHeaderClick={(e) => console.log(e)}
            menuItemRender={(item, dom) => (
              <div
                onClick={() => {
                  setPathname(item.path || "/welcome");
                }}
              >
                {dom}
              </div>
            )}
            {...settings}
          ></ProLayout>
        </ConfigProvider>
      </ProConfigProvider>
    </div>
  );
};
